/**
 * 数値入力ボックスコンポーネント
 * （実態はただのテキストボックス）
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import './NumberField.css';

class NumberField extends Component {
  constructor(props) {
    super(props);
    this.state = { value: props.value };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ value: nextProps.value });
  }

  handleChange(event) {
    const { name, maxLength = 0 } = this.props;
    let value = this.input.value;
    // 半角数字のみ
    value = value.replace(/[^\d]/g, '');
    // 最大入力桁制限
    if (maxLength > 0 && value.length > maxLength) {
      value = value.slice(0, maxLength);
    }
    this.setState({ value }, () => {
      if (this.props.propagate(name, value) !== false) {
        this.props.onChange(name, value);
      }
    });
  }

  handleBlur(event) {
    const { name } = this.props;
    const value = this.input.value;
    this.setState({ value }, () => {
      if (this.props.propagate(name, value, true) !== false) {
        this.props.onBlur(name, value);
      }
    });
  }

  render() {
    // eslint-disable-next-line no-unused-vars
    const { name, value, className, style, disabled, maxLength, onChange, onBlur, propagate, ...other } = this.props;
    return (
      <div className="NumberFieldContainer">
        <input
          {...other}
          type="text"
          id={name}
          name={name}
          className={classNames('NumberField', className, {
            'disabled': disabled,
          })}
          style={Object.assign({}, (maxLength > 0) ? { minWidth: `${maxLength}em` } : null, style)}
          value={this.state.value}
          disabled={disabled}
          maxLength={maxLength}
          onChange={this.handleChange.bind(this)}
          onBlur={this.handleBlur.bind(this)}
          ref={input => this.input = input}
        />
      </div>
    );
  }
}

NumberField.propTypes = {
  name: PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
    id: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    choices: PropTypes.array.isRequired,
  })]).isRequired,                      // id
  value: PropTypes.string,              // 入力値（初期値）
  className: PropTypes.string,          // class属性
  style: PropTypes.object,              // style属性
  disabled: PropTypes.bool,             // disabled属性
  maxLength: PropTypes.number,          // maxlength属性
  onChange: PropTypes.func,             // change event handler
  onBlur: PropTypes.func,               // blur event handler
  propagate: PropTypes.func.isRequired, // 親stateを更新するcallback
}

NumberField.defaultProps = {
  value: '',            // 初期値なし
  disabled: false,
  onChange: () => {},
  onBlur: () => {},
  propagate: () => {},
}

export default NumberField
